package cn.hahah.module.blog.service.users;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.hahah.module.blog.controller.admin.users.vo.*;
import cn.hahah.module.blog.dal.dataobject.users.UsersDO;
import cn.hahah.framework.common.pojo.PageResult;
import cn.hahah.framework.common.pojo.PageParam;
import cn.hahah.framework.common.util.object.BeanUtils;

import cn.hahah.module.blog.dal.mysql.users.UsersMapper;

import static cn.hahah.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.hahah.module.blog.enums.ErrorCodeConstants.*;

/**
 * 博客系统用户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UsersServiceImpl implements UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public Long createUsers(UsersSaveReqVO createReqVO) {
        // 插入
        UsersDO users = BeanUtils.toBean(createReqVO, UsersDO.class);
        usersMapper.insert(users);
        // 返回
        return users.getId();
    }

    @Override
    public void updateUsers(UsersSaveReqVO updateReqVO) {
        // 校验存在
        validateUsersExists(updateReqVO.getId());
        // 更新
        UsersDO updateObj = BeanUtils.toBean(updateReqVO, UsersDO.class);
        usersMapper.updateById(updateObj);
    }

    @Override
    public void deleteUsers(Long id) {
        // 校验存在
        validateUsersExists(id);
        // 删除
        usersMapper.deleteById(id);
    }

    private void validateUsersExists(Long id) {
        if (usersMapper.selectById(id) == null) {
            throw exception(USERS_NOT_EXISTS);
        }
    }

    @Override
    public UsersDO getUsers(Long id) {
        return usersMapper.selectById(id);
    }

    @Override
    public PageResult<UsersDO> getUsersPage(UsersPageReqVO pageReqVO) {
        return usersMapper.selectPage(pageReqVO);
    }

}